package com.power.web;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.power.model.TCustomer;
import com.power.query.CustomerQuery;
import com.power.result.CustomerExcelData;
import com.power.result.R;
import com.power.service.CustomerService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
public class CustomerController {
    @Resource
    private CustomerService customerService;

    @PostMapping("/api/customer")
    public R addCustomer(@RequestBody CustomerQuery customerQuery, @RequestHeader("token") String token) {
        customerQuery.setToken(token);
        Boolean isSuccess = customerService.addCustomer(customerQuery);
        return isSuccess ? R.OK() : R.FAIL();
    }

    @GetMapping("/api/customer")
    public R getCustomerListByPage(@RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage,
                                   @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
                                   CustomerQuery customerQuery) {
        PageInfo<TCustomer> pageInfo = customerService.selectCustomerListByPage(currentPage, pageSize, customerQuery);
        return R.OK(pageInfo);
    }

    /**
     * 文件下载（失败了会返回一个有部分数据的Excel）
     * <p>
     * 1. 创建excel对应的实体对象 参照{@link CustomerExcelData}
     * <p>
     * 2. 设置返回的 参数
     * <p>
     * 3. 直接写，这里注意，finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
     */
    @GetMapping("/api/customer/exportExcel")
    public void exportExcel(HttpServletResponse response, @RequestParam(value = "ids", required = false) String ids) throws Exception {
        // 响应类型是一个流
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("客户数据", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        //必须要设置头:key必须是Content-disposition，第二个参数前半部分必须是attachment;，表示是附件，浏览器会直接下载，剩余的部分是写文件名称
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<String> idsList = StringUtils.hasText(ids) ? Arrays.asList(ids.split(",")) : new ArrayList<>();
        List<CustomerExcelData> customerExcelDataList = customerService.getCustomerByExcel(idsList);
        EasyExcel.write(response.getOutputStream(), CustomerExcelData.class).sheet("模板").doWrite(customerExcelDataList);
    }
}
